package servicos;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;

import resposta.CabecalhoResposta;
import resposta.Resposta;
import sessao.Sessao;
import util.Servico;
import beans.Cliente;
import beans.Cookie;
import dao.ClienteDao;
import factory.DaoFactory;

public class ListarClientes implements Servico {
	private Sessao sessao =  Sessao.getSessao();
	private ClienteDao clienteDao = DaoFactory.getClienteDao();
	private Charset charset = Charset.forName("UTF-8");
	private ArrayList<String> blocos = new ArrayList<String>();
	private ArrayList<Cliente> clientes = new ArrayList<Cliente>();
	private Path pathInicio = Paths.get("trabalho3bi/alterarClienteInicio.html");		
	private Path pathMeio = Paths.get("trabalho3bi/alterarClienteMeio.html");	
	private Path pathFim = Paths.get("trabalho3bi/alterarClienteFim.html");	
	private Path pathFinal = Paths.get("trabalho3bi/listarClientes.html");
	
	public ListarClientes(){
		
	}
	
	@Override
	public void executa(Resposta resposta) {
		String cook = resposta.getRequisicao().getCabecalho().getValor("Cookie");	
		if(cook.length() > 1){
			String parts[] = cook.split("=");
			Cookie cookie = new Cookie(parts[0].trim(),parts[1].trim());
			if(sessao.validarCookie(cookie)){							
				gerarHtmlMeio(resposta);
				gerarHtmlFinal();
				
				String root = "trabalho3bi";
				resposta.setRoot(root);
				String recurso = "listarClientes.html";
				resposta.setRecurso(recurso);
				File file = new File(root+"\\"+recurso);
				CabecalhoResposta cabecalhoResposta = new CabecalhoResposta(file.length(), "text/html");				
				resposta.setCabecalhoResposta(cabecalhoResposta);
				resposta.despacharCabecalho();
				resposta.despacharRecurso();
				
				
				
			}else{
				negarAcesso(resposta);
			}
		}else{
			negarAcesso(resposta);			
		}
		
	}
	private void gerarHtmlFinal() {
		blocos = new ArrayList<String>();
		try(BufferedReader reader = Files.newBufferedReader(pathInicio, charset)) {
			String linha = null;
			while((linha = reader.readLine()) != null){
				blocos.add(linha);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try(BufferedReader reader = Files.newBufferedReader(pathMeio, charset)) {
			String linha = null;
			while((linha = reader.readLine()) != null){
				blocos.add(linha);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try(BufferedReader reader = Files.newBufferedReader(pathFim, charset)) {
			String linha = null;
			while((linha = reader.readLine()) != null){
				blocos.add(linha);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try(BufferedWriter writer = Files.newBufferedWriter(pathFinal, charset)) {
			Iterator<String> iterator = blocos.iterator();
			while(iterator.hasNext()){
				String s = iterator.next();
				writer.append(s,0,s.length());
				writer.newLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void gerarHtmlMeio(Resposta resposta) {		
		String meio = "";
		try {
			clientes = (ArrayList<Cliente>) clienteDao.getClientes();
			for (Cliente cliente : clientes) {
				meio ="<tr><form method=\"post\" action=\"/ManterCliente\"><input type=\"hidden\" name=\"id\" value=\""+
						cliente.getId()+"\"><td><input type=\"text\" required name=\"nome\" value=\""+
						cliente.getNome()+"\" size=30></td><td><input type=\"text\" required name=\"endereco\" value=\""+
						cliente.getEndereco()+"\" size=30></td><td><input type=\"text\" required name=\"cidade\" value=\""+
						cliente.getCidade()+"\" size=30></td><td><input type=\"text\" required name=\"estado\" value=\""+
						cliente.getEstado()+"\" size=10></td><td><input type=\"text\" required name=\"cep\" value=\""+
						cliente.getCep()+"\" size=10></td><td><input type=\"text\" required name=\"email\" value=\""+
						cliente.getEmail()+"\" size=20></td><td><input type=\"submit\" name=\"alterar\" value=\"Alterar\"></td>"
						+ "<td><input type=\"submit\" name=\"excluir\" value=\"Excluir\"></td></form></tr>"; 
				blocos.add(meio);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}		
		try (BufferedWriter writer = Files.newBufferedWriter(pathMeio, charset)){
			Iterator<String> iterator = blocos.iterator();
			while(iterator.hasNext()){
				meio = iterator.next();
				writer.append(meio, 0, meio.length());
				writer.newLine();
			}					
		} catch (Exception e) {
			// TODO: handle exception
		}		
	}

	private void negarAcesso(Resposta resposta){
		System.err.println("entrou aqui");
		String root = "titanic\\";
		resposta.setRoot(root);
		resposta.setRecurso("sessaoExpirada.html");
		File file = new File(root+"\\sessaoExpirada.html");
		CabecalhoResposta cabecalhoResposta = new CabecalhoResposta(file.length(), "text/html");
		resposta.setCabecalhoResposta(cabecalhoResposta);
		resposta.despacharCabecalho();
		resposta.despacharRecurso();
	}
	
	private String getInicioHtml(){
		String inicio ="<!doctype html>		<html lang=\"en\"><head><link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\" /><meta charset=\"utf-8\" /><title>"
				+ "Sistemas distribuidos</title></head><body><fieldset><legend>Clientes</legend><div id=\"menu\"><div class=\"itensMenu\"><a href=\"FormCadastroCliente\">"
				+ "<button>Cadastrar</button></a></div><div class=\"itensMenu\"><a href=\"ListarClientes\"><button>Listar</button></a></div></div></fieldset><fieldset id=\"listar\">"
				+ "<legend>Clientes cadastrados</legend><table border=\"1\"><tr><td width=\"15%\">Nome</td><td width=\"15%\">Endereço</td><td width=\"15%\">Cidade</td>"
				+ "<td width=\"5%\">Estado</td><td width=\"5%\">Cep</td><td width=\"10%\">Email</td><td width=\"5%\">Editar</td><td width=\"5%\">Excluir</td></tr>";
		return inicio;
	}
	private String getFimHtml(){
		 String fim = "</table></fieldset></body></html>";
		 return fim;
	}
}
